#include "../include/determinant.h"

#include <stdio.h>
#include <stdlib.h>

#include "../include/algorithm.h"

void initDeterminant(Determinant *d) {
    // 输入行列式阶数(不安全)
    printf("请输入行列式阶数:");
    scanf("%d", &(d->rank));
    // 给行列式的数组分配空间
    d->inner_array = (int **)malloc(d->rank * sizeof(int *));
    if (d->inner_array == NULL) {
        // 说明内存分配失败直接输出错误信息
    }
    d->inner_array[0] = (int *)malloc(d->rank * d->rank * sizeof(int));
    if (d->inner_array[0] == NULL) {
        // 说明内存分配失败直接输出错误信息
    }
    // 为各个指针分配首地址
    for (int i = 1; i < d->rank; i++) {
        d->inner_array[i] = d->inner_array[i - 1] + d->rank;
    }
    // 输入行列式中的值(不安全)
    for (int i = 0; i < d->rank; i++) {
        for (int j = 0; j < d->rank; j++) {
            scanf("%d", &d->inner_array[i][j]);
        }
    }
}

int calcDeterminant(Determinant d) {
    int ans = 0;
    // 计算出n个数的全排列
    int **permutations = allPermutaion(d.rank);
    // 得到全排列的数量
    int number_permutations = getFactorial(d.rank);
    for (int i = 0; i < number_permutations; i++) {
        int sign =
            getReverseOrderNumber(permutations[i], d.rank) % 2 == 0 ? 1 : -1;
        int multi = 1;
        for (int j = 0; j < d.rank; j++) {
            multi *= d.inner_array[j][permutations[i][j]];
        }
        ans += sign * multi;
    }
    free(permutations[0]);
    free(permutations);
    return ans;
}